'use strict';
	angular.module('accounting.periodCaptionInitial', ['app.services'])

	.controller('periodCaptionInitialCtrl'
			,['$rootScope', '$scope', 'BizData', '$uibModal', '$ocLazyLoad', f])
    function f($rootScope, $scope, BizData, $uibModal, $ocLazyLoad) {
		
		var common = require('common');

		var Model = this;
		
		//获取会计开账年月
	    Model.getInfo = function(){
	    	$.LoadingOverlay("show");
			$.ajax({
	            type: "GET",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/accounting/paramSetting/getInfo",
	            data: {},
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	            	$.LoadingOverlay("hide");
	                // Play with returned data in JSON format
					console.log('data->',data);
					if(data.code==0){
						$scope.dataConfigure = data.data;
				    	$scope.kjkzny = $scope.dataConfigure.kjkzny;
						Model.refresh();
						$scope.$apply();
					}else{
						alert(data.info);
					}
	            },
	            error: function (msg) {
	            	$.LoadingOverlay("hide");
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };
	    
	    Model.getInfo();
	    
		
	    $scope.pattKjkzny = /[1-2][0-9][0-9][0-9]-(0[1-9]|1[0-2])/g;
	    
	    Model.ok = function(){
	    	//更新开账年月
//	    	if(!kjkzny || kjkzny.length!=7){
//	    		alert('格式不正确。例如：2020-02才正确');
//	    	}
	    	//console.log('kjkzny-->>',kjkzny);
	    	//正则表达式
//	    	var str = "123456789";
//	    	var patt1 = /[1-4]/g;
//	    	var result = str.match(patt1);
	    	  
	    	//var patt1 = "/(0?[1-9]|1[0-2])/g";//正则表达式千万千万不能加双引号在两端！！！！！！！！！！！！！
	    	//var patt1 = /(0?[1-9]|1[0-2])/g;//经测试，正常使用。
	    	var patt1 = /[1-2][0-9][0-9][0-9]-(0[1-9]|1[0-2])/g;
	    	var result = $scope.kjkzny.match(patt1);
//	    	var result = $scope.pattKjkzny.test($scope.kjkzny);
	    	alert(result);
	    	//if(result==null) alert('输入值不符合正则表达式：'+patt1);
	    	if(result==false){ 
	    		alert('输入值不符合正则表达式：'+$scope.pattKjkzny);
	    		return;
	    	}
	    	
	    	//开账
	    	Model.initial();
	    }
	    
		$scope.rowStyle = function(row){
			//if(row.nodeKind.value=='nkLeaf') return {}; else return {'font-weight': 'bold'};
			if(row.nodeKind.value=='nkLeaf') return {}; else return {'color': 'lightslategrey'};
			//if(row.nodeKind.value=='nkLeaf') return {}; else return {'background-color': 'lightgrey'};
		};
		
		//ng-stype
		$scope.nameStyle = function(row){
			//console.log('nameStyle.row-->',row);
			var nodeLevel = row.nodeLevel.value;
			var textIndent = (nodeLevel - 1)*2;
			//var obj = {color:'red'};
			//var obj = {'background-color':'blue'};
			//var obj = {'text-indent':'2em'};
			var obj = {};
			obj['text-indent'] = textIndent + 'em'//'2em';
			
			return obj;
		};
		
		//开账
	    Model.initial = function(){

	    	var options = {};
	    	options.yearPeriodNo = $scope.kjkzny;
	    	
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/accounting/periodCaption/calculate/initial",
	            data: JSON.stringify(options),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
					console.log('data->',data);
					if(data.code==0){
						Model.getInfo();
					}else{
						alert(data.info);
					}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };
	    
		//清除开账数据
	    Model.clear = function(){

	    	var options = {};
	    	options.yearPeriodNo = $scope.kjkzny;
	    	
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/accounting/periodCaption/calculate/delete",
	            data: JSON.stringify(options),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
					console.log('data->',data);
					if(data.code==0){
						Model.getInfo();
					}else{
						alert(data.info);
					}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };
	    
		
		//结束开账（将录入的数据分配到各个列，禁止继续维护数据）
	    Model.initSubmit = function(){

	    	var options = {};
	    	options.yearPeriodNo = $scope.kjkzny;
	    	
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/accounting/periodCaption/calculate/initSubmit",
	            data: JSON.stringify(options),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
					console.log('data->',data);
					if(data.code==0){
						Model.getInfo();
					}else{
						alert(data.info);
					}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };
		
		//取消结束（将分配到各个列的数据撤回，以便继续维护数据）
	    Model.initActive = function(){

	    	var options = {};
	    	options.yearPeriodNo = $scope.kjkzny;
	    	
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/accounting/periodCaption/calculate/initActive",
	            data: JSON.stringify(options),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
					console.log('data->',data);
					if(data.code==0){
						Model.getInfo();
					}else{
						alert(data.info);
					}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };
		
	    /*
		//试算平衡
	    Model.initTrial = function(){

	    	var options = {};
	    	options.yearPeriodNo = $scope.kjkzny;
	    	
			$.ajax({
	            type: "POST",
	            async : true,//异步（默认），同步为false
	            url: $rootScope.getProjectName() + "/accounting/periodCaption/calculate/initTrial",
	            data: JSON.stringify(options),
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function (data) {
	                // Play with returned data in JSON format
					console.log('initTrial.data->',data);
					if(data.code==0){
						alert('完成');
						//Model.getInfo();
					}else{
						//alert(data.info);
					}
	            },
	            error: function (msg) {
	                alert('ajax调用错误信息：'+msg.responseText);
	            }
	        });
	    };
	    */
	    
		//试算平衡弹出窗口
	    Model.initTrialPop = function(){
			//打开对话框
			var options = {};
			options.kjkzny = $scope.kjkzny;
			
	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	templateUrl: $rootScope.getProjectName() + $rootScope.viewprefix + '/accounting/periodCaption/trialpop' + $rootScope.viewsuffix,  
	            controller: 'trialpopCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '期初开账--试算平衡'; }
                    ,loadCtrl : $ocLazyLoad.load('js/accounting/periodCaption/trialpop')
		        }
	        });  
	        //模态窗口打开之后执行的函数
	        modalInstance.opened.then(function(){  
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (result) {  
	             //成功关闭窗口
	        }, function (reason) {  
	        	
	        });  
		};


		
		//循环递归调用，向上一级累加（这一种不可行。如：先填写200，自动加至上一级，再改为0怎么办？）
		/*
		Model.addUp = function(rowID, column, value) {
			var oldValue = Model.dataMaster.getValue(column,rowID);
			var newValue = common.accAdd(oldValue,value);
			Model.dataMaster.setValue(column,newValue,rowID);
			var fParent = Model.dataMaster.getValue('fParent',rowID);
			return fParent;
		};
		*/

	    //所以，应该使用由逐层向上的由父级汇总
		Model.aggregateUp = function(rowID, column) {
			var fID;//行的主记录ID，行中的captionID与发Parent对应，维持会计科目的树形关系
			var total = 0;
			for(var i=0;i<Model.dataMaster.rows.length;i++){
				//汇总child之和
				if(Model.dataMaster.rows[i].fParent.value==rowID){
					var value = Model.dataMaster.rows[i][column].value;
					total = common.accAdd(total,value);
				}
				//找到当前行
				if(Model.dataMaster.rows[i].captionID.value==rowID){
					fID = Model.dataMaster.rows[i].fID.value;
				}
			}
			Model.dataMaster.setValue(column,total,fID);
			var fParent = Model.dataMaster.getValue('fParent',fID);
			return fParent;
		};
	    
		
		
		Model.dataMasterAfterRefresh = function(event) {
			//console.log('dataMasterAfterRefresh-->',event);
		};
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			console.log('dataMasterValueChanged.event-->>',event);

			if(event.column=='balanceYearBegin'){
				//年初余额：需要处理年初借方和年初贷方余额，还要分别处理上一级的数据
				//balanceYearBegin = (debitYearBegin - creditYearBegin)*direction
				var rowID = event.source.getID(event.rowIndex);
				var dob = event.source.getValue('dob',rowID);
				if(dob>0){
					//借方
					var debitYearBegin = event.value;
					event.source.setValue('debitYearBegin',debitYearBegin,rowID);
//					var debitYear = event.source.getValue('debitYear',rowID);
//					var debitYearEnd = common.accAdd(debitYearBegin,debitYear);
//					event.source.setValue('debitYearEnd',debitYearEnd,rowID);
				}
				if(dob<0){
					//贷方
					var creditYearBegin = event.value;
					event.source.setValue('creditYearBegin',creditYearBegin,rowID);
//					var creditYear = event.source.getValue('creditYear',rowID);
//					var creditYearEnd = common.accAdd(creditYearBegin,creditYear);
//					event.source.setValue('creditYearEnd',creditYearEnd,rowID);
				}
//				var debitYearEnd = event.source.getValue('debitYearEnd',rowID);
//				var creditYearEnd = event.source.getValue('creditYearEnd',rowID);
//				var balanceYearEnd = common.accMul(common.accSub(debitYearEnd,creditYearEnd),dob);
//				event.source.setValue('balanceYearEnd',balanceYearEnd,rowID);
			}
			/*
			if(event.column=='debitYear'){
				//本年累计借方金额，还要处理上一级的数据
				var rowID = event.source.getID(event.rowIndex);
				var dob = event.source.getValue('dob',rowID);
				var debitYear = event.value;
				var debitYearBegin = event.source.getValue('debitYearBegin',rowID);
				var debitYearEnd = common.accAdd(debitYearBegin,debitYear);
				event.source.setValue('debitYearEnd',debitYearEnd,rowID);
				var creditYearEnd = event.source.getValue('creditYearEnd',rowID);
				var balanceYearEnd = common.accMul(common.accSub(debitYearEnd,creditYearEnd),dob);
				event.source.setValue('balanceYearEnd',balanceYearEnd,rowID);
				//卷算上一级
				//...
			}
			if(event.column=='creditYear'){
				//本年累计贷方金额，还要处理上一级的数据
				var rowID = event.source.getID(event.rowIndex);
				var dob = event.source.getValue('dob',rowID);
				var creditYear = event.value;
				var creditYearBegin = event.source.getValue('creditYearBegin',rowID);
				var creditYearEnd = common.accAdd(creditYearBegin,creditYear);
				event.source.setValue('creditYearEnd',creditYearEnd,rowID);
				var debitYearEnd = event.source.getValue('debitYearEnd',rowID);
				var balanceYearEnd = common.accMul(common.accSub(debitYearEnd,creditYearEnd),dob);
				event.source.setValue('balanceYearEnd',balanceYearEnd,rowID);
				//卷算上一级
				//...
			}
			*/
			
			if(event.column=='balanceBegin'){
				//期初余额：需要处理期初借方和年贷方余额，还要分别处理上一级的数据
				//balanceBegin = (debitBegin - creditBegin)*direction
				var rowID = event.source.getID(event.rowIndex);
				var dob = event.source.getValue('dob',rowID);
				if(dob>0){
					//借方
					event.source.setValue('debitBegin',event.value,rowID);
					//event.source.setValue('debitEnd',event.value,rowID);
				}
				if(dob<0){
					//贷方
					event.source.setValue('creditBegin',event.value,rowID);
					//event.source.setValue('creditEnd',event.value,rowID);
				}
				//event.source.setValue('balanceEnd',event.value,rowID);
			}
			
			
			if(event.column=='balanceYearBegin' || event.column=='debitYear' || event.column=='creditYear' || event.column=='balanceBegin'){
				var rowID = event.source.getID(event.rowIndex);
				var fParent = event.source.getValue('fParent',rowID);
				//console.log('fParent-->>',fParent);
				//好像无需循环调用
				/*
				while(fParent){
					fParent = Model.aggregateUp(fParent,event.column);
				}
				*/
				if(fParent){
					Model.aggregateUp(fParent,event.column);
				}
			}
		};
		
		
		//修改
		Model.edit = function(){
			Model.dataMaster.editData();
		};
		
		//保存
		Model.save = function() {
			Model.dataMaster.saveData();
		};

		//取消编辑
		Model.saveCancel = function() {
			Model.dataMaster.editCancel();
		};
	    
		//刷新数据
		Model.refresh = function(){
			console.log('$scope.kjkzny-->>',$scope.kjkzny);
			if($scope.kjkzny){
				var yearNo = $scope.kjkzny.split("-")[0];
				var periodNo = $scope.kjkzny.split("-")[1];
				console.log('yearNo-->>',yearNo);
				console.log('periodNo-->>',periodNo);
				Model.dataMaster.setFilter('yearNo',"PeriodCaption.yearNo='"+yearNo+"'")
				Model.dataMaster.setFilter('periodNo',"PeriodCaption.periodNo='"+periodNo+"'")
				Model.dataMaster.refreshData();
			}
		}
		

		
		var options = {};
		options.container = Model;
		options.concept = 'PeriodCaption';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.reader = '/accounting/periodCaption/list/query';
		options.writer = '/accounting/periodCaption/list/save';
		options.deleter = '';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = '';
		options.master = {"data":"","relation":""};
		options.directDeleteMode = false;
		options.orderBy = 'captionNo ASC';
		options.limit = -1;
		
		options.onAfterRefresh = Model.dataMasterAfterRefresh;
		options.onValueChanged = Model.dataMasterValueChanged;

		Model.dataMaster = new BizData(options);

		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		//设置过滤条件
		//Model.dataMaster.filter = " StorageRecordDetail.billType<>'ZCJC' ";

		////////////////////启动执行结束///////////////////////////////////////////////////
		
		
	    return Model;
		
	}	
	
